const KoaRouter = require('koa-router');

let Router = new KoaRouter()

const UserlModel = require('../../../models/User');

const bcrypt = require('bcryptjs'); //密码加密模块
/* 
    @route POST /register
    @params {userName,passWord}
    @desc 注册接口
*/
Router.post('/',async (ctx)=>{
    let userName = ctx.request.body.userName
    let passWord = ctx.request.body.passWord

    // 检查用户名是否存在
    const findResult = await UserlModel.find({userName:userName})

    if(findResult.length == 0){
        const newUser = await new UserlModel({
            userName:userName,
            passWord:passWord
        })

        //  对密码进行加密
        let salt = bcrypt.genSaltSync(10);
        let hash = bcrypt.hashSync(newUser.passWord, salt);
        newUser.passWord = hash
        // 保存
        await newUser.save().then((result) => {
            ctx.body = {
                code:0,
                data:{
                    userName:userName
                },
                message:'注册成功'
            }
        }).catch((err) => {
            ctx.body = {
                code:0,
                data:{
                    userName:userName
                },
                message:'注册失败'
            }
        });
        
    }else{
        ctx.body = {
            code:1,
            message:'已存在相同用户名'
        }
    }
    
})


module.exports = Router.routes();